package cn.bone.base.jms2;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * Created by MD-01 on 2016/9/12.
 * Queue队列方式发送点对点消息数据
 */
public class QueueSender {
    //发送次数
    private static final int SEND_NUM = 5;
    //tcp地址
    private static final String BROCK_URL = "tcp://localhost:61616";
    //目标, 在activeMQ管理员控制台创建http://localhost:8161/admin/queues.jsp
    private static final String DESTINATION = "cn.bone.queue";

    public static void sendMessage(QueueSession session, javax.jms.QueueSender sender) throws Exception {
        for (int i = 0; i < SEND_NUM; i++) {
            String message = "发送消息第" + (i + 1) + "条";
            MapMessage map = session.createMapMessage();
            map.setString("text", message);
            map.setLong("time", System.currentTimeMillis());
            System.out.println(map);
            sender.send(map);
        }
    }

    public static void run() throws Exception {

        QueueConnection connection = null;
        QueueSession session = null;

        //创建连接工厂
        QueueConnectionFactory factory = new ActiveMQConnectionFactory(
                ActiveMQConnection.DEFAULT_USER,
                ActiveMQConnection.DEFAULT_PASSWORD,
                BROCK_URL);

        //通过工厂创建一个连接
        connection = factory.createQueueConnection();
        //启动连接
        connection.start();
        //创建一个session会话
        session = connection.createQueueSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);

        //创建一个消息队列
        Queue queue = session.createQueue(DESTINATION);
        //创建消息发送者
        javax.jms.QueueSender sender = session.createSender(queue);
        //设置持久化模式
        sender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

        sendMessage(session, sender);
        //提交会话
        session.commit();

        session.close();
        connection.close();
    }

    public static void main(String[] args) {

        try {
            run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
